<template>
  <div class="rank-page" :style="{ background: currentConfig.mainAreaBg }">
    <!-- 活动时间信息 -->
    <div class="time-info">
      <div class="end-time" :style="{ color: currentConfig.activeTitleColor }">
        {{ endTime }} 结束
      </div>
      <div class="countdown">
        距离活动结束：
        <span
          >{{ remainingTime.days }} 天 {{ remainingTime.hours }} 时
          {{ remainingTime.minutes }} 分 {{ remainingTime.seconds }} 秒</span
        >
      </div>
    </div>

    <!-- 搜索框 -->
    <!-- <van-search v-model="searchValue" placeholder="搜索" class="search-box" /> -->

    <!-- 排行榜标题 -->
    <div class="rank-title" :style="currentConfig.button">票数排行榜</div>

    <!-- 冠亚季军展示 -->
    <div class="ranking-top">
      <div
        class="ranking-item"
        v-for="(item, index) in topThree"
        :key="index"
        @click="voteForPlayer(item)"
        :class="{ first: index === 0, second: index === 1, third: index === 2 }"
      >
        <div class="rank-tag" v-if="index === 0">NO.1</div>
        <div class="rank-tag" v-else-if="index === 1">NO.2</div>
        <div class="rank-tag" v-else>NO.3</div>
        <van-image
          round
          fit="cover"
          :src="
            item.imageUrl && item.imageUrl.trim()
              ? item.imageUrl
              : require('@/assets/list_touxiang.png')
          "
          class="avatar"
        />
        <p class="contestant-id">{{ item.name }}</p>
        <p class="votes">{{ item.voteCount }}票数</p>
      </div>
    </div>

    <!-- 其他演员列表 -->
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
      :error.sync="error"
      error-text="请求失败，点击重新加载"
    >
      <van-cell
        v-for="(item, index) in otherContestants"
        :key="index"
        :title="item.name"
        :label="`票数: ${item.voteCount}`"
        @click="voteForPlayer(item)"
      >
        <template #icon>
          <van-image
            style="width: 60px; height: 60px; margin: 0 10px 0 0"
            round
            fit="cover"
            :src="
              item.imageUrl && item.imageUrl.trim()
                ? item.imageUrl
                : require('@/assets/list_touxiang.png')
            "
          />
        </template>
      </van-cell>
    </van-list>

    <!-- 弹窗组件 -->
    <PlayerDetails
      :childrenData="passPlayerData"
      @add-event="handleAddEvent"
      @child-event="handleChildEvent"
    ></PlayerDetails>
    <AddTickets
      :childrenAddData="passAddData"
      @AddTickets-event="AddTicketsEvent"
    ></AddTickets>
  </div>
</template>

<script>
import { Toast, Dialog } from "vant";
import PlayerDetails from "./PlayerModule/PlayerDetails.vue"; //投票
import AddTickets from "../view/AddTickets.vue";
import { styleConfig } from "@/utils/voteH5StyleConfigs.js";
import {
  playerList,
  rankList,
  getPlayerDetail,
  activeInfo,
} from "../api/index.js";
export default {
  name: "RankingPage",
  components: {
    PlayerDetails,
    AddTickets,
  },
  computed: {
    // 计算当前模板对应的样式配置
    currentConfig() {
      return styleConfig[this.templateId] || styleConfig[1];
    },
    // 可以单独定义需要的样式属性（如背景色）
    mainAreaBg() {
      return this.currentConfig.mainAreaBg;
    },
  },
  data() {
    return {
      activityId: "",
      templateId: 1,
      // 倒计时相关
      days: 0,
      hours: 0,
      minutes: 0,
      seconds: 0,
      // 冠亚季军数据（示例）
      topThree: [],
      // 其他演员数据（示例，用于列表演示）
      otherContestants: [],

      page: {
        pageNum: 1,
        pageSize: 10,
      },

      total: 0, // 总数据条数（从接口获取）
      list: [],
      loading: false,
      finished: false,
      error: false, //提示错误信息
      emptyState: false, //初始空状态
      passPerData: {
        show: false,
        buttonStyle: "",
        activeInfo: {},
      },
      passPlayerData: {
        passCurrentConfig: {},
        show: false,
        playerItem: {},
      },
      passAddData: {
        passCurrentConfig: {},
        show: false,
        playerItem: {},
      },

      everyDay: {}, // 一个投票者每天投多少票
      startTime: "",
      endTime: "",
      activityInfo: null,
      // 新增：剩余时间相关
      remainingTime: {
        days: 0,
        hours: 0,
        minutes: 0,
        seconds: 0,
      },
    };
  },
  mounted() {
    // 1. 优先从 localStorage 获取数据（页面刷新后不丢失）
    this.activityId =
      localStorage.getItem("vote_activityId") || this.sharedData.activityId;
    this.templateId =
      Number(localStorage.getItem("vote_templateId")) ||
      this.sharedData.templateId;

    // 2. 验证数据有效性
    if (!this.activityId) {
      Toast.fail("未获取到活动ID");
      return;
    }
    if (this.activityId) {
      this.fetchInitialData();
    } else {
      // 容错：提取失败时用默认ID，避免页面卡死
      this.activityId = "479c4a01a85440c693ac19ee55f6c68a";
      this.fetchInitialData();
    }
    this.initCountdown();
    this.currentConfig;
    console.log("🚀 ~ mounted ~ this.currentConfig:", this.currentConfig);
  },
  methods: {
    // 获取活动信息
    async fetchInitialData() {
      try {
        // 显示统一加载提示
        this.$toast.loading({
          message: "加载中...",
          forbidClick: true,
          duration: 0,
        });

        if (!this.activityId) {
          this.$toast.fail("未找到活动ID");
          return;
        }

        // 只请求活动详情接口，移除演员列表接口的并行请求
        const activityResponse = await activeInfo(this.activityId);

        // 处理活动详情响应
        console.log(
          "🚀 ~ fetchInitialData ~ activityResponse:",
          activityResponse
        );
        if (activityResponse.data && activityResponse.data.code === 0) {
          this.activityInfo = activityResponse.data.data;
          console.log(
            "🚀 ~ fetchInitialData ~ this.activityInfo:",
            this.activityInfo
          );
          this.everyDay = JSON.parse(this.activityInfo.voteSettings);
          console.log("🚀 ~ fetchInitialData ~ this.everyDay:", this.everyDay);
          this.startTime = activityResponse.data.data.startTime; //2025-09-02 00:00:00
          this.endTime = activityResponse.data.data.endTime; //2025-10-28 00:00:00
          // const time_yu  计算剩余时间
          // 关键：初始化剩余时间计算
          this.initRemainingTime(); //2025-10-28 00:00:00
        } else {
          this.$toast.fail(activityResponse.data?.msg || "获取活动信息失败");
        }
      } catch (error) {
        console.error("初始数据加载失败:", error);
        this.$toast.fail("网络异常，数据加载失败");
      } finally {
        // 关闭加载提示
        this.$toast.clear();
      }
    },
    // 解析时间字符串为Date对象（处理"2025-09-02 00:00:00"格式）
    parseTime(timeStr) {
      const [datePart, timePart] = timeStr.split(" ");
      const [year, month, day] = datePart.split("-").map(Number);
      const [hours, minutes, seconds] = timePart.split(":").map(Number);
      // 注意：月份是0-based（0-11），所以要减1
      return new Date(year, month - 1, day, hours, minutes, seconds);
    },

    // 计算剩余时间并更新状态
    calculateRemainingTime() {
      const now = new Date();
      const start = this.parseTime(this.startTime);
      const end = this.parseTime(this.endTime);

      // 判断活动状态
      if (now < start) {
        this.activityStatus = "pending";
        this.remainingTime = { days: 0, hours: 0, minutes: 0, seconds: 0 };
      } else if (now > end) {
        this.activityStatus = "ended";
        this.remainingTime = { days: 0, hours: 0, minutes: 0, seconds: 0 };
        // 活动结束后清除定时器
        if (this.timer) {
          clearInterval(this.timer);
          this.timer = null;
        }
      } else {
        this.activityStatus = "active";
        // 计算剩余毫秒数
        const remainingMs = end - now;
        // 转换为天、时、分、秒
        this.remainingTime = {
          days: Math.floor(remainingMs / (1000 * 60 * 60 * 24)),
          hours: Math.floor(
            (remainingMs % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)
          ),
          minutes: Math.floor((remainingMs % (1000 * 60 * 60)) / (1000 * 60)),
          seconds: Math.floor((remainingMs % (1000 * 60)) / 1000),
        };
      }
    },

    // 初始化剩余时间计算（启动定时器）
    initRemainingTime() {
      // 先清除已有定时器，避免重复
      if (this.timer) {
        clearInterval(this.timer);
      }
      // 立即计算一次
      this.calculateRemainingTime();
      // 每秒更新一次
      this.timer = setInterval(() => {
        this.calculateRemainingTime();
      }, 1000);
    },
    // 投票：检查本地openId和userInfo后打开详情页
    async voteForPlayer(item) {
      try {
        // 1. 从本地存储读取关键信息（避免依赖this.currentUser，直接读本地更可靠）
        const localOpenId = localStorage.getItem("openId") || "";
        const localNickname = localStorage.getItem("nickname") || "";
        const localAvatar = localStorage.getItem("avatar") || "";

        // 2. 检查条件1：是否已登录（openId存在且非空）
        if (!localOpenId.trim()) {
          Toast.fail("请先登录后再投票");
          // 引导用户登录
          this.authorizeLogin();
          return;
        }

        // 3. 检查条件2：是否已获取完整userInfo（nickname和avatar非空）
        if (!localNickname.trim() || !localAvatar.trim()) {
          Toast.fail("请授权获取用户信息后再投票");
          // 引导用户授权获取用户信息
          await this.redirectToUserInfoAuth();
          // 授权后重新检查，满足则打开详情页
          const updatedNickname = localStorage.getItem("nickname") || "";
          if (updatedNickname.trim()) {
            this.openVoteDetails(item);
          }
          return;
        }
        // 5. 所有条件满足，打开投票详情页
        await this.fetchPlayerDetailAndOpen(item);
        this.openVoteDetails(item);
      } catch (error) {
        console.error("投票前校验失败:", error);
        Toast.fail("操作失败，请稍后重试");
      }
    },
    async fetchPlayerDetailAndOpen(item) {
      try {
        // 2. 核心：调用 getPlayerDetail 接口（仅传选手ID，不处理返回数据）
        await getPlayerDetail(item.id);
        console.log("getPlayerDetail 接口调用成功（选手ID：", item.id, "）");
      } catch (error) {
        // 3. 接口调用失败：仅打印日志+提示，不阻断打开详情页
        console.error("getPlayerDetail 接口调用失败:", error);
        Toast.fail({
          message: "详情接口请求失败",
          duration: 3000,
        });
      } finally {
        // 4. 无论接口成功/失败，都关闭加载提示并打开详情页
        Toast.clear();
      }
    },
    // 新增：复用打开投票详情页的逻辑（避免重复代码）
    openVoteDetails(item) {
      this.passPlayerData = {
        passCurrentConfig: this.currentConfig,
        show: true,
        playerItem: item, // 传递选手信息到详情页
      };
    },

    //返回首页正常关闭所有弹窗 接受值  关闭弹框
    handleChildEvent(data) {
      console.log("data:", data);
      this.passPerData.show = data.isShow;
      this.passPlayerData.show = data.isShow;
    },
    // 回返详情页
    AddTicketsEvent(data) {
      console.log("data:", data);
      this.passAddData.show = data.isShow;
      this.passPlayerData.show = true;
      console.log("🚀 ~ AddTicketsEvent ~ !data.isShow:", !data.isShow);
    },
    handleAddEvent(data, palyerItem) {
      this.passPlayerData.show = data.isShow;
      // this.passAddData.show = true;
      this.passAddData = {
        show: true,
        passCurrentConfig: this.currentConfig,
        playerItem: palyerItem, // 传递选手信息到详情页
      };
      console.log(
        "🚀 ~ handleAddEvent ~ his.passAddData.show:",
        this.passAddData.show
      );
    },
    // 初始化倒计时
    initCountdown() {
      const endTime = new Date("2025-08-20 11:00:00").getTime();
      const timer = setInterval(() => {
        const now = new Date().getTime();
        const diff = endTime - now;
        if (diff <= 0) {
          clearInterval(timer);
          this.days = 0;
          this.hours = 0;
          this.minutes = 0;
          this.seconds = 0;
          return;
        }
        this.days = Math.floor(diff / (1000 * 60 * 60 * 24));
        this.hours = Math.floor(
          (diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)
        );
        this.minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
        this.seconds = Math.floor((diff % (1000 * 60)) / 1000);
      }, 1000);
    },
    // 关键：请求排行榜数据（依赖 activityId）
    async getRankingData() {
      try {
        this.loading = true;
        // 调用排行榜接口（传递 activityId 和分页参数）
        const response = await rankList(
          this.activityId,
          {
            page: this.currentPage,
            pageSize: this.pageSize,
          } // 按票数降序
        );

        if (response.data && response.data.code === 0) {
          const list = response.data.data || [];
          // 分离冠亚季军和其他演员
          this.topThree = list.slice(0, 3);
          this.otherContestants = list.slice(3);
          // 更新结束时间（从接口获取真实时间）
          this.endTime =
            this.endTime ||
            response.data.extra?.endTime ||
            "2025-08-20 11:00:00";
        } else {
          Toast.fail(response.data?.msg || "获取排行榜数据失败");
        }
      } catch (error) {
        console.error("获取排行榜数据失败:", error);
        Toast.fail("网络异常，无法加载排行榜");
      } finally {
        this.loading = false;
      }
    },
    // 投诉按钮点击事件
    handleComplain() {
      // 可在此实现投诉逻辑，比如弹出投诉表单等
      this.$toast("点击了投诉按钮");
    },
    // 列表滚动加载数据
    onLoad() {
      this.loading = true; //加载数据
      this.getPlayerList(); // 请求后端数据铺设界面
    },
    // 排行榜
    async getPlayerList() {
      let { page } = this;
      await rankList(this.activityId, this.page)
        .then((res) => {
          console.log("res:", res);
          if (res.data.code == 0) {
            console.log("res排行榜列表:", res);
            this.loading = false; // 加载关闭
            // 遍历 list 数组，修改 tbImageslList 中的 tbImage 键名为 url
            const listNew = res.data.data.players || [];
            this.list = this.list.concat(listNew);
            this.topThree = this.list.slice(0, 3);
            this.otherContestants = this.list.slice(3);
            console.log("this.list :", this.list);
            ++this.page.pageNum;
            if (!res.data.data.players.length) {
              this.finished = true;
              return;
            }
          } else {
            this.finished = true;
            this.loading = false; // 加载关闭
          }
        })
        .catch((error) => {
          console.log("🚀 ~ getPlayerList ~ error:", error);
          //抛出错误
          this.error = true; //显示点击加载更多
          this.emptyState = true; // 区分初始渲染没数据
          this.refreshing = false;
          this.loading = false;
        });
    },
  },
};
</script>

<style scoped>
.rank-page {
  padding: 16px;
  background-color: #f7f8fa;
  min-height: 100vh;
}

.time-info {
  text-align: center;
  margin-bottom: 20px;
}

.end-time {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 8px;
}

.countdown {
  font-size: 18px;
  font-weight: 500;
  color: #ee0a24;
}

.search-box {
  margin-bottom: 20px;
}

.rank-title {
  font-size: 18px;
  font-weight: bold;
  text-align: center;
  margin-bottom: 16px;
  color: #333;
  background-color: #00cdaf;
  color: #fff;
  padding: 9px 0px;
}

.rank-content {
  margin-bottom: 20px;
}
.ranking-page {
  background-color: #fff;
}
.top-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  background-color: #fff;
}
.complain-btn {
  padding: 6px 12px;
}
.ranking-title {
  margin-top: 10px;
}
.ranking-top {
  display: flex;
  justify-content: space-around;
  padding: 10px;
}
.ranking-item {
  width: 30%;
  text-align: center;
}
.ranking-item.first {
  color: #ffd700; /* 金色，可根据实际设计调整 */
}
.ranking-item.second {
  color: #c0c0c0; /* 银色 */
}
.ranking-item.third {
  color: #cd7f32; /* 铜色 */
}
.rank-tag {
  font-size: 12px;
  font-weight: bold;
  margin-bottom: 5px;
}
.avatar {
  width: 60px;
  height: 60px;
  margin: 0 auto 5px;
}
.contestant-id {
  font-size: 12px;
  margin-bottom: 3px;
}
.votes {
  font-size: 12px;
}
.van-cell {
  margin-bottom: 10px;
}
</style>
